package com.unitedats.common.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

import org.apache.commons.lang.ArrayUtils;


public class FileUtil {

	private static String[] uploadFiles(Collection<Part> fileTypeParts, String fieldName) throws IOException,
			FileNotFoundException {

		List<String> uploadedFilesNames = new ArrayList<String>();
		// Common.log(fileTypeParts.toString());
		if (fileTypeParts != null && fileTypeParts.size() > 0 && fieldName != null) {

			Object[] objects = fileTypeParts.toArray();
			// Part[] fileTypePartsAry = (Part[]) fileTypeParts.toArray();
			OutputStream out = null;
			InputStream filecontent = null;

			try {
				for (int i = 0; i < objects.length; i++) {
					Part p = (Part) objects[i];
					String fileName = null;
					if (uploadedFile(p) && fieldName.equals(p.getName())) {

						fileName = fieldName + Default.FILE_NAME_SEPARATOR + getTimeStampString()
								+ Default.FILE_NAME_SEPARATOR + getFileName(p);
						File file = new File(Default.FILES_UPLOAD_DIR + fileName);
						out = new FileOutputStream(file);
						filecontent = p.getInputStream();

						int read = 0;
						byte[] bytes = new byte[1024];

						while ((read = filecontent.read(bytes)) != -1)
							out.write(bytes, 0, read);

						uploadedFilesNames.add(fileName);
					}
				}
			} finally {
				if (out != null)
					out.close();

				if (filecontent != null)
					filecontent.close();
			}
		}
		return (uploadedFilesNames.size() == 0) ? null : (String[]) uploadedFilesNames
				.toArray(new String[uploadedFilesNames.size()]);
	}

	public static Collection<Part> getUploadedFileTypeParts(Collection<Part> allParts) {
		Collection<Part> uploadedFileTypeParts = new ArrayList<Part>();
		for (Part p : allParts)
			if (uploadedFile(p))
				uploadedFileTypeParts.add(p);
		return uploadedFileTypeParts;
	}

	public static boolean uploadedFile(Part part) {
		String sentFileName = getFileName(part);
		if (sentFileName != null && !sentFileName.isEmpty())
			return true;
		return false;
	}

	public static String[] uploadFiles(HttpServletRequest request, String fieldName) throws IOException,
			FileNotFoundException, ServletException {
		String[] ary1 = uploadFiles(request.getParts(), fieldName);
		// Common.log("ary 1 length is ************ " + ary1.length);
		String[] ary2 = request.getParameterValues(fieldName + "_PrevUploadedFiles");
		// if (ary2 != null)
		// Common.log("ary 2 length is ************ " + ary2.length);
		// Common.log("ary 1 + ary 2 length is ************ " +
		// ArrayUtils.addAll(ary1, ary2).length);
		return (String[]) ArrayUtils.addAll(ary1, ary2);
	}

	public static String getFileName(Part part) {
		// String partHeader = part.getHeader("content-disposition");
		// Logger.log(Level.INFO, "Part Header = {0}", partHeader);
		for (String content : part.getHeader("content-disposition").split(";"))
			if (content.trim().startsWith("filename"))
				return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
		return null;
	}

	protected synchronized static String getTimeStampString() {
		return new Timestamp(new Date().getTime()).toString().replaceAll(" ", "_").replaceAll(":", "");
	}

	public static void main(String[] args) {
		String s = "f1_2014-06-05_150535.305_box.gif";
		Common.log(s.substring(s.lastIndexOf("_") + 1));
	}
}
